﻿using Microsoft.EntityFrameworkCore;
using S.Transplantation.Infrastructure.S.TransplantationDbContext;

namespace S.Transplantation.Infrastructure
{
    public class BaseRepository<T> : IBaseRepository<T> where T : class
    {
        public DescendantTransfersDbContext db { get; }

        public BaseRepository(DescendantTransfersDbContext db)
        {
            this.db = db;
        }

        public bool Add(T t)
        {
            db.Set<T>().Add(t);
            return db.SaveChanges() > 0;
        }

        public bool Delete(int id)
        {
            var list = db.Set<T>().Find(id);
            db.Set<T>().Remove(list);
            return db.SaveChanges() > 0;
        }

        public IQueryable<T> GetAll()
        {
            return db.Set<T>().AsQueryable();
        }

        public bool Update(T t)
        {
            db.Set<T>().Update(t);
            return db.SaveChanges() > 0;
        }

        #region 异步增删改查方法

        public async Task<bool> AddAsync(T t)
        {
            db.Set<T>().AddAsync(t);
            return await db.SaveChangesAsync() > 0;
        }

        public async Task<bool> DeleteAsync(int id)
        {
            var list = await db.Set<T>().FindAsync(id);
            db.Set<T>().Remove(list);
            return await db.SaveChangesAsync() > 0;
        }

        public async Task<bool> UpdateAsync(T t)
        {
            db.Set<T>().Update(t);
            return await db.SaveChangesAsync() > 0;
        }

        public async Task<List<T>> GetAllAsync()
        {
            return await db.Set<T>().ToListAsync();
        }

        #endregion 异步增删改查方法

        public Task<int> AddRangeAsync(IEnumerable<T> t)
        {
            db.Set<T>().AddRangeAsync(t);
            return db.SaveChangesAsync();
        }

        public Task<int> UpdateRangeAsync(IEnumerable<T> t)
        {
            db.Set<T>().UpdateRange(t);
            return db.SaveChangesAsync();
        }

        public int RemoveRange(IEnumerable<T> t)
        {
            db.Set<T>().RemoveRange(t);
            return db.SaveChanges();
        }
    }
}